using AdminApiTemplate.Common.Helpers;

namespace AdminApiTemplate.Tasks
{
    public class TaskService
    {
        private readonly MySqlHelper _defaultQuery;

        public TaskService(
            MySqlHelper defaultQuery)
        {
            _defaultQuery = defaultQuery;
        }

        /// <summary>
        /// 增加执行记录
        /// </summary>
        /// <param name="request"></param>
        public string AddExecuteLog(AddExecuteLogRequest request)
        {
            var sql = "INSERT INTO TaskExecuteLog(CreateTime,CostTime,Message,Success,TaskId,TaskName) VALUES(NOW(),@CostTime,@Message,@Success,@TaskId,@TaskName);";
            _defaultQuery.Execute(sql, request);
            return "添加成功";
        }

        /// <summary>
        /// 获取可以执行的任务
        /// </summary>
        /// <returns></returns>
        public List<GetNextTaskListResponseItem> GetCanExecuteTaskList()
        {
            var sql = "SELECT * FROM TaskItem t1 WHERE t1.CanExecute = 1;";
            var items = _defaultQuery.GetList<GetNextTaskListResponseItem>(sql);
            return items;
        }

        /// <summary>
        /// 获取即将执行的任务
        /// </summary>
        /// <returns></returns>
        public List<GetNextTaskListResponseItem> GetNextTaskList()
        {
            var sql = "SELECT * FROM TaskItem t1 WHERE t1.CanExecute = 1 AND t1.NextExecuteTime < NOW();";
            var items = _defaultQuery.GetList<GetNextTaskListResponseItem>(sql);
            return items;
        }

        /// <summary>
        /// 更新下次执行时间
        /// </summary>
        /// <param name="id"></param>
        /// <param name="nextExecuteTime"></param>
        public string UpdateNextExecuteTime(int id, DateTime nextExecuteTime)
        {
            var sql = "UPDATE TaskItem SET NextExecuteTime = @nextExecuteTime WHERE Id = @id;";
            _defaultQuery.Execute(sql, new { id, nextExecuteTime });
            return "更新成功";
        }
    }
}
